﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.IO;

namespace MvcDatagrid.Models
{
    public class PictureRepository: IPicturesRepository, IDisposable
    {
        private NorthwindEntities _db;

        private NorthwindEntities db
        {
            get
            {
                if (_db == null)
                {
                    _db = new NorthwindEntities();
                }
                return _db;
            }
        }
        public IEnumerable<Images> GetAllPictures()
        {
            return db.Images;
        }

        public Images GetPictureById(int Id)
        {
            return db.Images.Single(e => e.Id == Id);
        }
        public int AddPicture(Images img)
        {
            db.Images.AddObject(img);
            return db.SaveChanges();
        }

        public int UpdatePicture(Images img)
        {
            if(img.EntityState == EntityState.Detached)
                db.Images.Attach(img);
            db.ObjectStateManager.ChangeObjectState(img, EntityState.Modified);
            return db.SaveChanges();
        }

        public int DeletePicture(Images img)
        {
            db.Images.DeleteObject(img);
            return db.SaveChanges();
        }

        public void Dispose()
        {
            if (_db == null)
            {
                return;
            }
            else
            {
                _db.Dispose();
                _db = null;
            }
        }
    }
}